/****** Object:  Stored Procedure OfficesGetList    Script Date: Friday, March 07, 2008 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spOfficesGetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [spOfficesGetList]
GO

	
	
	
/******************************************************************************
**		File: 
**		Name: spOfficesGetList
**		Desc: 
**
**		Return values:
** 
**		Called by:   
**              
**		Parameters:
**		Input							Output
**     ----------							-----------
**
**		Auth: CodeSmith
**		Date: 3/7/2008 11:26:46 AM
*******************************************************************************
**		Change History
*******************************************************************************
**		Date:		Author:				Description:
**		--------		--------				-------------------------------------------
**    
*******************************************************************************/
CREATE PROCEDURE spOfficesGetList
	@OrderBy varchar(50),
	@OrderDirection varchar(5),
	@Page int,
	@PageSize int,
	@TotalRecords int output
AS

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

CREATE TABLE #TempOffices (
	RowNumber INT IDENTITY (1, 1) NOT NULL,
	OfficeID int	
)

DECLARE @sql nvarchar(2000)

-- insert primary keys into temp table
SET @sql =	N'INSERT INTO #TempOffices ([OfficeID]) SELECT '
IF (@PageSize > 0)
	SET @sql = @sql + ' TOP ' + CAST(@Page*@PageSize as nvarchar) 

SET @sql = @sql + ' [OfficeID] FROM [Offices]  ORDER BY [' + @OrderBy + N'] ' + @OrderDirection

EXEC (@sql)

SELECT @TotalRecords = COUNT(*) FROM [Offices]

SELECT
	[Offices].[OfficeID],
	[OfficeName],
	[OfficeCode],
	[NotifyEmailEnable],
	[SortOrder]
FROM
	#TempOffices AS tblTemp JOIN [Offices] ON
	tblTemp.OfficeID = [Offices].OfficeID 	
WHERE (@PageSize = 0) OR (@PageSize > 0 AND (@Page - 1)*@PageSize < RowNumber AND RowNumber <= @Page*@PageSize)
ORDER BY RowNumber

DROP TABLE #TempOffices

GO

	
